package com.xiaochen.manager.service.impl;

import com.xiaochen.manager.mapper.SysRoleMenuMapper;
import com.xiaochen.manager.mapper.SysRoleUserMapper;
import com.xiaochen.manager.service.SysMenuService;
import com.xiaochen.manager.service.SysRoleMenuService;
import com.xiaochen.model.dto.system.AssginMenuDto;
import com.xiaochen.model.entity.system.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        // 1.先查询所有的菜单
        List<SysMenu> sysMenuList = sysMenuService.findNodes();
        // 2.再查询角色分配过的菜单id列表
        List<Long> roleMenuIds = sysRoleMenuMapper.findSysRoleMenuByRoleId(roleId);
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("sysMenuList", sysMenuList);
        stringObjectMap.put("roleMenuIds",roleMenuIds);
        return stringObjectMap;
    }

    /**
     * 分配菜单
     * @param assginMenuDto
     */
    @Transactional
    @Override
    public void doAssign(AssginMenuDto assginMenuDto) {
        // 1.如果角色之前分配过菜单需要删除
        sysRoleMenuMapper.deleteById(assginMenuDto.getRoleId());
        // 2.保存分配的菜单数据
        List<Map<String, Number>> menuInfo = assginMenuDto.getMenuIdList();
        if (menuInfo != null && menuInfo.size() > 0){
            sysRoleMenuMapper.doAssign(assginMenuDto);
        }
    }
}
